﻿Imports System.Data.OleDb
Public Class Connect

    Protected Function ConnectionData() As OleDbConnection
        Try
            Dim str As String
            str = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = PTNK.mdb"
            Dim cn As New OleDbConnection(str)
            cn.Open()
            Return cn
        Catch ex As OleDbException
            Throw New Exception(ex.Message.ToString)
        End Try
    End Function

    ''' <summary>
    ''' Hàm lấy mã
    ''' </summary>
    ''' <param name="tenbang">Bảng cần tham chiếu để lấy mã</param>
    ''' <param name="tencot">Cột chứa Mã</param>
    ''' <param name="kytu">Ký tự bắt đầu của mã</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function LayMa(ByVal tenbang As String, ByVal tencot As String) As String
        Dim cn As New OleDbConnection
        cn = Me.ConnectionData()
        Dim sql As String
        sql = "select " & tencot & " from " & tenbang & " order by " & tencot
        Dim cmd As New OleDbCommand(sql, cn)
        Dim dr As OleDbDataReader
        dr = cmd.ExecuteReader
        Dim arrlist As New List(Of Integer)
        Dim so As Integer
        Dim numdigit As Integer
        Dim kytu As String
        While dr.Read
            Dim num As Integer = 0
            Dim length As Integer = 0
            Dim str As String = dr.GetString(0)
            Dim c() As Char = str.ToCharArray(0, str.Length)
            For i As Integer = 0 To str.Length - 1
                If Char.IsLetter(c(i)) = True Then
                    length += 1
                End If
                If Char.IsNumber(c(i)) = True Then
                    num += 1
                End If
            Next
            numdigit = num
            Dim maso As String = str.Substring(length)
            Dim chiso As Integer = CType(maso, Integer)
            arrlist.Add(chiso)
            kytu = str.Substring(0, length)
        End While
        Dim flag As Integer = 0
        Dim dem As Integer = 0
        For i As Integer = 0 To arrlist.Count - 1

            If i + 1 = arrlist(i) Then
                dem += 1
            End If
            If i + 1 <> arrlist(i) Then
                so = i + 1
                Exit For
            End If
        Next
        If dem = arrlist.Count Then
            flag = 1
        End If
        If flag = 1 Then
            arrlist.Sort()
            so = arrlist(arrlist.Count - 1) + 1
        End If
        Dim format As String = "{0:D" + numdigit.ToString + "}"
        Dim strSo As String = String.Format(format, so)
        Dim ma As String
        ma = kytu + strSo
        Return ma
    End Function

    Public Sub New()

    End Sub
End Class
